// pages/club/list.js
const clubApi = require('../../api/club');

Page({
  data: {
    clubs: [],
    keyword: '',
    page: 1,
    pageSize: 20,
    loading: false,
    hasMore: true
  },

  onLoad(options) {
    this.loadClubs();
  },

  /**
   * 加载俱乐部列表
   */
  loadClubs(reset = false) {
    if (this.data.loading) return;
    if (!reset && !this.data.hasMore) return;

    const page = reset ? 1 : this.data.page;
    this.setData({ loading: true });

    const params = {
      page,
      page_size: this.data.pageSize,
      keyword: this.data.keyword || undefined
    };

    clubApi.getClubList(params)
      .then(data => {
        const newClubs = data.items || [];

        this.setData({
          clubs: reset ? newClubs : [...this.data.clubs, ...newClubs],
          page: page + 1,
          hasMore: newClubs.length >= this.data.pageSize,
          loading: false
        });
      })
      .catch(err => {
        console.error('加载俱乐部列表失败:', err);
        this.setData({ loading: false });
      });
  },

  /**
   * 搜索
   */
  onSearch(e) {
    const keyword = e.detail.value.trim();
    this.setData({ 
      keyword,
      page: 1,
      hasMore: true
    });
    this.loadClubs(true);
  },

  /**
   * 加载更多
   */
  loadMore() {
    this.loadClubs(false);
  },

  /**
   * 导航到详情页
   */
  navigateToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/club/detail?id=${id}`
    });
  },

  /**
   * 导航到创建页
   */
  navigateToCreate() {
    const app = getApp();
    app.checkLogin().then(() => {
      wx.navigateTo({
        url: '/pages/club/create'
      });
    }).catch(() => {});
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({ page: 1, hasMore: true });
    this.loadClubs(true);
    wx.stopPullDownRefresh();
  },

  /**
   * 分享
   */
  onShareAppMessage() {
    return {
      title: '发现有趣的运动俱乐部',
      path: '/pages/club/list'
    };
  }
});

